<template>
  <list-grid ref="fileListGrid" v-if="fileList && fileList.length > 0">
    <list-grid-item v-for="(file, index) in fileList" :key="index" :is-small="true">
      <el-link type="primary" @click="downloadFile(file.fileName, file.filePath)" :underline="false" slot="title"
               :title="file.fileName"
               :style="{width: editable ? 'calc(100% - 12px)' : '100%'}">
        <div class="file-name">
          <svg-icon :icon-class="fileIcon(file.fileName)" class-name="file-icon"></svg-icon>
          <span>{{ file.fileName }}</span>
        </div>
      </el-link>
      <el-link v-if="editable" :underline="false" @click="handleDelete(index)" type="danger" slot="extra">删除</el-link>
    </list-grid-item>
  </list-grid>
</template>

<script>
import {ListGrid, ListGridItem} from '@/components/ListGrid';

export default {
  name: "FileList",
  components: {
    ListGrid,
    ListGridItem
  },
  props: {
    // 值
    fileList: Array,
    editable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      downloadFileUrl: process.env.VUE_APP_BASE_API + "/file/download",
      icons: {
        bmp: "picture",
        gif: "picture",
        jpg: "picture",
        jpeg: "picture",
        png: "picture",
        doc: "word",
        docx: "word",
        xls: "excel",
        xlsx: "excel",
        ppt: "powerpoint",
        pptx: "powerpoint",
        txt: "txt",
        rar: "zip",
        zip: "zip",
        pdf: "pdf",
        default: "file"
      }
    };
  },
  methods: {
    getFileExtension(fileName) {
      return fileName.slice(fileName.lastIndexOf(".") + 1);
    },
    fileIcon(fileName) {
      const fileExtension = this.getFileExtension(fileName);
      return this.icons[fileExtension] || this.icons["default"];
    },
    downloadFile(fileName, filePath) {
      window.open(`${this.downloadFileUrl}?fileName=${encodeURIComponent(fileName)}&filePath=${encodeURIComponent(filePath)}`);
    },
    handleDelete(index) {
      this.$emit("delete", index);
    }
  }
}
</script>

<style scoped lang="scss">
  .file-name {
    display: flex;
    flex-direction: row;
    align-content: center;
    justify-content: flex-start;
    padding: 2px 6px;

    .file-icon {
      font-size: 16px;
      margin-right: 6px;
      margin-top: 1px;
    }
  }
</style>
